package com.example.config;

import com.example.pojo.User;
import com.example.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;
    //一进入授权页面就会调用该方法
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行授权doGetAuthorizationInfo");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//        info.addStringPermission("user:add");//添加权限

        //拿到当前登录的这个对象
        Subject subject = SecurityUtils.getSubject();
        //拿到user对象
        User currentUser = (User)subject.getPrincipal();//在认证返回值构造方法的principal换成user
        info.addStringPermission(currentUser.getPerms());//设置当前用户的权限

        return info;//返回添加认证的信息
    }

    //一进入认证页面就会调用该方法
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行认证doGetAuthenticationInfo");
        //只要进入自定义的登录认证页，就会走到这个方法。

//        //用户名、密码 数据中取
//        String name = "root";
//        String password = "root";

        UsernamePasswordToken userToken = (UsernamePasswordToken) token;

        //连接真实的数据库 为什么能识别user里的用户 因为这里用到了userservice的方法
        User user = userService.queryUserByName(userToken.getUsername());
        if(user==null){
            return null;
        }

        //首页登录按钮显示
        //Subject currentSubject = SecurityUtils.getSubject();
        //Session session = currentSubject.getSession();
        //session.setAttribute("loginUser",user);

//        if(!userToken.getUsername().equals(name)){
//            return null;//抛出异常 unknownAccountException
//        }
//        //密码认证，shiro做

        return new SimpleAuthenticationInfo(user,user.getPwd(),"");
    }
}
